package com.ningxun.pagent.web.controller.bus;

import com.ningxun.pagent.bus.domain.BusPolicyContent;
import com.ningxun.pagent.bus.service.IBusPolicyContentService;
import com.ningxun.pagent.common.annotation.Log;
import com.ningxun.pagent.common.core.controller.BaseController;
import com.ningxun.pagent.common.enums.BusinessType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 政策内容导出控制器
 */
@RestController
@RequestMapping("/bus/policy")
public class BusPolicyController extends BaseController {

    @Autowired
    private IBusPolicyContentService busPolicyContentService;

    /**
     * 导出单条政策为 Word 文件，文件名为 policyId.docx
     */
    @PreAuthorize("@ss.hasPermi('bus:policy:export')")
    @Log(title = "政策内容", businessType = BusinessType.EXPORT)
    @GetMapping("/exportWord/{policyId}")
    public void exportWord(@PathVariable("policyId") Long policyId, HttpServletResponse response) {
        try {
            BusPolicyContent policy = busPolicyContentService.selectBusPolicyContentByPolicyId(policyId);
            if (policy == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            String fileName = policyId + ".docx";
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            String encoded = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=" + encoded + "; filename*=UTF-8''" + encoded);

            try (XWPFDocument doc = new XWPFDocument(); ServletOutputStream out = response.getOutputStream()) {
                // 标题
                if (StringUtils.isNotBlank(policy.getTitle())) {
                    XWPFParagraph titlePara = doc.createParagraph();
                    titlePara.setAlignment(ParagraphAlignment.CENTER);
                    XWPFRun titleRun = titlePara.createRun();
                    titleRun.setText(policy.getTitle());
                    titleRun.setBold(true);
                    titleRun.setFontSize(16);
                }

                // 内容（将HTML转为纯文本，保留基本换行）
                String content = defaultStripHtml(policy.getContent());
                if (StringUtils.isNotBlank(content)) {
                    XWPFParagraph p = doc.createParagraph();
                    p.setAlignment(ParagraphAlignment.BOTH);
                    XWPFRun run = p.createRun();
                    run.setFontSize(12);
                    for (String line : content.split("\n")) {
                        run.setText(line);
                        run.addBreak();
                    }
                }

                doc.write(out);
                out.flush();
            }
        } catch (Exception e) {
            // 简单失败处理
            try { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (Exception ignore) {}
        }
    }

    /**
     * 兼容前端下载工具使用POST方式
     */
    @PreAuthorize("@ss.hasPermi('bus:policy:export')")
    @Log(title = "政策内容", businessType = BusinessType.EXPORT)
    @org.springframework.web.bind.annotation.PostMapping("/exportWord/{policyId}")
    public void exportWordPost(@PathVariable("policyId") Long policyId, HttpServletResponse response) {
        exportWord(policyId, response);
    }

    private String defaultStripHtml(String html) {
        if (html == null) return "";
        // 移除脚本与样式，避免将JS/CSS写入Word
        String text = html
                .replaceAll("(?is)<script[^>]*>.*?</script>", "")
                .replaceAll("(?is)<style[^>]*>.*?</style>", "");
        // 替换常见块级标签为换行，以保留段落
        text = text.replaceAll("(?i)<\\s*br\\s*/?\\s*>", "\n")
                .replaceAll("(?i)</p>", "\n")
                .replaceAll("(?i)</div>", "\n");
        // 移除其余标签
        text = text.replaceAll("<[^>]+>", "");
        // 解码基本实体
        text = text.replace("&nbsp;", " ")
                .replace("&amp;", "&")
                .replace("&lt;", "<")
                .replace("&gt;", ">");
        // 规范空白
        text = text.replaceAll("\r\n|\r", "\n");
        text = text.replaceAll("\n{3,}", "\n\n").trim();
        return text;
    }
}


